<?php
namespace app\common\model;
use app\common\service\WxPublic;
use think\model\concern\SoftDelete;
use think\Paginator;

class WechatQrCodeModel extends BaseModel
{
    use SoftDelete,TraitPay;

    const ORDER_EXP_TIME=7200;

    protected $table = 'wechat_qr_code';

    protected $json = ['pay_info'];

    public static $fields_is_fees =[
        ['name'=>'收费'],
        ['name'=>'免费'],
    ];

    public static $fields_pay_state = [
        ['name'=>'待付款'],
        ['name'=>'已付款'],
    ];

    public static $fields_pay_way = [
        ['name'=>'--'],
        ['name'=>'微信'],
    ];

    public static $fields_status = [
        ['name'=>'订单已关闭'],
        ['name'=>'待付款'],
        ['name'=>'扫码成功'],
        ['name'=>'已付款'],
        ['name'=>'已取消'],
    ];

    public function getStatusName()
    {
        return self::getPropInfo('fields_status',$this['status'],'name');
    }

    /**
     * 生成二维码
     * @param $type int 票据类型
     * @param $device_model DevicesModel 设备编号
     * @return WechatQrCodeModel|null
     *
     * @throws \Exception
     */
    public static function generateQrCode($type,DevicesModel $device_model)
    {
        $mch_model = empty($device_model['mch_id'])? null : MchMerchantModel::find($device_model['mch_id']);
        $model = new self();
        $model->setAttrs([
            'type'=>$type,
            'mch_id'=>$device_model['mch_id'],
            'device_id'=>$device_model['id'],
            'province'=>$mch_model['province'],
            'city'=>$mch_model['city'],
            'area'=>$mch_model['area'],

            'status'=>1,
        ]);
        $model->save();

        $current_time = time();
        $scene_str = $current_time.'_'.$device_model['id'].'_'.$model['id'];
        $wx_data = WxPublic::createQrcode($scene_str,3600);
        $expire_seconds = $wx_data['expire_seconds']??0;
        $is_fees = empty($device_model['is_fees']) ? 0 : $device_model['is_fees'];
        $money = empty($device_model['money'])?0:$device_model['money'];
        $dis_money = 0; //优惠额度
        $pay_money = $is_fees==1 ? 0 : $money;
        $model->setAttrs([
            'no'=>self::getDateNo("00"),
            'money'=> $money,
            'pay_money'=> $pay_money,
            'dis_money'=> $dis_money,
            'is_fees'=> $is_fees,
            'ticket'=>$wx_data['ticket']??'',
            'url'=>$wx_data['url']??'',
            'expire_seconds'=>$expire_seconds,
            'expire_time'=>date('Y-m-d H:i:s',$current_time+$expire_seconds-10),
        ]);
        $model->save();

        if(empty($model['pay_money'])){
            $model->_sure_pay(0);
        }

        //删除以前未支付的二维码产生的订单
        self::where([
            ['device_id','=',$model['device_id']],
            ['status','in', [1,2]],
            ['id','<>', $model['id']],
        ])->update([
            'status'=>0,
        ]);

        return $model;
    }


    public static function refreshQrCode(array $input_data = [])
    {
        $wqc_id = $input_data['wqc_id']??'';
        $model = self::find($wqc_id);
        return $model;
    }

    //获取状态说明
    public static function getRefreshStatusContent($status)
    {
        $content = "请关闭弹窗重新获取二维码";
        if($status==1){
            $content = "请使用微信扫描二维码";
        }elseif($status==2){
            $content = "您已扫码，请在微信公众号内完成支付后再进行下一步";
        }elseif($status==3){
            $content = "您已付款,即将进入答题流程";
        }elseif($status==4){
            $content = "二维码已失效,请关闭窗口重新获取二维码";
        }
        return $content;

    }

    //微信消息处理
    public function getWxMsgContent($type)
    {
        if($type==1){
            $url = url('/api/device/use',['id'=>$this['id']],false,true)->build();
            $content =  '<a href="'.$url.'">立即使用('.$this['id'].')</a>';
        }else{
            $content = '二维码已被其它人使用:'.$this['id'];
        }

        return $content;
    }

    public function getTempMsgContent($name)
    {
        $device_model = DevicesModel::find($this['device_id']);
        if($name=='no'){
            return $this['no'];
        }elseif($name=='name'){
            return $device_model['no'];
        }elseif($name=='money'){
            return $this['money'];
        }elseif($name=='create_time'){
            return $this['create_time'];
        }
        return $name;
    }


    public function handleScan($openid,$og_id)
    {
        if($this['status']==1){
            $this->setAttrs([
                'status'=>2,
                'og_id'=>$og_id,
                'openid'=>$openid,
                'scan_time'=>date('Y-m-d H:i:s'),
            ]);
            $this->save();
        }
        if($this['openid']==$openid){
            //给用户发送消息
            //发送支付链接
            $url = url('/device/usePay',['id'=>$this['id']],false,true)->build();

            WechatSendMsgLogsModel::sendUserMsg($this,1,$openid, ['m_type'=>0,'url'=>$url]);

//            $this->sendUserMsg($og_id,$openid,[
//                'type'=>'text',
//                'content'=>'<a href="'.$url.'">立即使用</a>',
//            ]);
        }else{
            WechatSendMsgLogsModel::sendUserMsg($this,2,$openid, ['m_type'=>0]);
//            $this->sendUserMsg($og_id,$openid,[
//                'type'=>'text',
//                'content'=>'二维码已被其它人使用',
//            ]);
        }

    }

    public function checkOrderPayState()
    {
        if(!empty($this['pay_state'])){
            throw new \Exception("订单未处于可支付状态");
        }
    }




}